package com.Lemon.Zhkuhealth.provider.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.Lemon.Zhkuhealth.common.pojo.entity.CheckGroup;
import com.Lemon.Zhkuhealth.common.pojo.entity.CheckGroupCheckItemXref;
import com.Lemon.Zhkuhealth.common.util.PageResult;
import com.Lemon.Zhkuhealh.api.service.ICheckGroupService;
import com.Lemon.Zhkuhealth.provider.mapper.CheckGroupCheckItemXrefMapper;
import com.Lemon.Zhkuhealth.provider.mapper.CheckGroupMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;


@DubboService
@RequiredArgsConstructor
public class CheckGroupServiceImpl extends ServiceImpl<CheckGroupMapper, CheckGroup> implements ICheckGroupService {

  private final CheckGroupMapper checkGroupMapper;
  private final CheckGroupCheckItemXrefMapper checkGroupCheckItemXrefMapper;

  @Override
  @Transactional
  public void save(CheckGroup checkGroup, List<Long> checkitemIds) {
    // 1. 保存检查组数据
    checkGroupMapper.insert(checkGroup);
    // 2. 保存检查组检查项关系表数据
    for (Long checkItemId : checkitemIds) {
      CheckGroupCheckItemXref checkGroupCheckItemXref = new CheckGroupCheckItemXref();
      checkGroupCheckItemXref.setCheckGroupId(checkGroup.getId());
      checkGroupCheckItemXref.setCheckItemId(checkItemId);
      checkGroupCheckItemXrefMapper.insert(checkGroupCheckItemXref);
    }
  }

  @Override
  public List<CheckGroup> list() {
    return checkGroupMapper.selectList(null);
  }

  @Override
  public PageResult<CheckGroup> page (
      Integer currentPage, Integer pageSize, String queryString) {
    LambdaQueryWrapper<CheckGroup> lambdaQueryWrapper = new LambdaQueryWrapper<>();
    lambdaQueryWrapper
        .like(null != queryString, CheckGroup::getCode, queryString)
        .or()
        .like(null != queryString, CheckGroup::getName, queryString)
        .or()
        .like(null != queryString, CheckGroup::getHelpCode, queryString);
    // 1. 通过分页参数创建分页对象
    Page<CheckGroup> page = new Page<>(currentPage, pageSize);
    // 2. 执行分页查询
    checkGroupMapper.selectPage(page, lambdaQueryWrapper);
    // 3. 返回分页结果
    return new PageResult<>(page.getTotal(), page.getRecords());
  }

  @Override
  public CheckGroup getById(Long id) {
    return checkGroupMapper.selectById(id);
  }

  @Override
  public List<Long> listCheckItemIdsByCheckGroupId(Long id) {
    QueryWrapper<CheckGroupCheckItemXref> queryWrapper =
        new QueryWrapper<CheckGroupCheckItemXref>().eq("checkgroup_id", id);
    List<CheckGroupCheckItemXref> checkGroupCheckItemXrefList =
        checkGroupCheckItemXrefMapper.selectList(queryWrapper);
    List<Long> checkItemIds =
        checkGroupCheckItemXrefList.stream()
            .map(CheckGroupCheckItemXref::getCheckItemId)
            .collect(Collectors.toList());
    return checkItemIds;
  }

  @Override
  @Transactional
  public void update(CheckGroup checkGroup, List<Long> checkItemIds) {
    // 1. 更新检查组信息
    checkGroupMapper.updateById(checkGroup);
    // 2. 找出现有关系
    QueryWrapper<CheckGroupCheckItemXref> queryWrapper
            = new QueryWrapper<CheckGroupCheckItemXref>().eq("checkgroup_id", checkGroup.getId());
    List<CheckGroupCheckItemXref> checkGroupCheckItemXrefs = checkGroupCheckItemXrefMapper.selectList(queryWrapper);
    List<Long> existingCheckItemIds = checkGroupCheckItemXrefs.stream().map(CheckGroupCheckItemXref::getCheckItemId).toList();
    // 3. 找出需要删除的关系
    List<Long> checkItemIdsToDelete = existingCheckItemIds.stream().filter(id -> !checkItemIds.contains(id)).toList();
    // 4. 找出需要新增的关系
    List<Long> checkItemIdsToAdd = checkItemIds.stream().filter(id -> !existingCheckItemIds.contains(id)).toList();
    // 5. 删除不需要的关系
    if (!checkItemIdsToDelete.isEmpty()) {
      QueryWrapper<CheckGroupCheckItemXref> queryWrapperDelete =
              new QueryWrapper<CheckGroupCheckItemXref>()
                      .eq("checkgroup_id", checkGroup.getId())
                      .in("checkitem_id", checkItemIdsToDelete);
      checkGroupCheckItemXrefMapper.delete(queryWrapperDelete);
    }
    // 6. 新增需要的关系
    for (Long checkItemId : checkItemIdsToAdd) {
      CheckGroupCheckItemXref checkGroupCheckItemXref = new CheckGroupCheckItemXref();
      checkGroupCheckItemXref.setCheckGroupId(checkGroup.getId());
      checkGroupCheckItemXref.setCheckItemId(checkItemId);
      checkGroupCheckItemXrefMapper.insert(checkGroupCheckItemXref);
    }

  }
  /**
   * 删除检查组及其关联的检查项
   * 必须是事务性的，以保证数据一致性
   * @param id 检查组ID
   */
  @Override
  @Transactional // 确保删除操作在同一个事务中，保证数据一致性
  public void deleteById(Long id) {
    // 1. 删除检查组与检查项的关联数据
    // 使用 LambdaQueryWrapper 删除关联表中 checkGroupId 等于传入 id 的所有记录
    checkGroupCheckItemXrefMapper.delete(Wrappers.<CheckGroupCheckItemXref>lambdaQuery()
            .eq(CheckGroupCheckItemXref::getCheckGroupId, id));

    // 2. 删除检查组本身
    // 调用 Mybatis-Plus 提供的 ServiceImpl 的 removeById 方法删除主表数据
    this.removeById(id);
  }

}
